package com.kisyou.JDBC使用;

import com.mysql.cj.jdbc.MysqlDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * SQL 注入（SQL Inject）
 */
public class SQL注入 {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        String username = scanner.nextLine();

        MysqlDataSource dataSource =  new MysqlDataSource();
        dataSource.setUser("debian-sys-maint");
        dataSource.setPassword("co7lI761pHOFy9gx");
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3307/jdbc_mysql?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai");

        try(Connection connection = dataSource.getConnection()){
            String sql = "select * from users where username = '%s'";
            try(PreparedStatement preparedStatement = connection.prepareStatement(sql)){

                /**
                 * 当用户输入用户名是类型 "  ' or 1 = 1 or 1 = '  "
                 * String sql = "select * from users where username = '' or 1 = 1 or 1 = '' ";
                 * 此时变成了 username = ''     or     1 = 1      or     1 = ''
                 * 也就是这个判断条件恒为 1
                 * 此时即发生了SQL注入
                 */
                sql = String.format(sql, username);

                try(ResultSet resultSet = preparedStatement.executeQuery()){

                }
            }
        }
    }
}
